"""
配置模块初始化文件
提供配置加载和管理功能
"""

import yaml
import os
from pathlib import Path
from typing import Dict, Any
import logging

# 配置文件路径
CONFIG_DIR = Path(__file__).parent
CONFIG_FILE = CONFIG_DIR / "config.yaml"

logger = logging.getLogger(__name__)


class Config:
    """配置管理类，单例模式"""
    
    _instance = None
    _config: Dict[str, Any] = {}
    
    def __new__(cls):
        """单例模式实现"""
        if cls._instance is None:
            cls._instance = super(Config, cls).__new__(cls)
            cls._instance._load_config()
        return cls._instance
    
    def _load_config(self):
        """加载YAML配置文件"""
        try:
            if CONFIG_FILE.exists():
                with open(CONFIG_FILE, 'r', encoding='utf-8') as f:
                    self._config = yaml.safe_load(f)
                logger.info(f"配置文件加载成功: {CONFIG_FILE}")
            else:
                logger.warning(f"配置文件不存在: {CONFIG_FILE}")
                self._config = {}
        except Exception as e:
            logger.error(f"配置文件加载失败: {e}")
            self._config = {}
    
    def get(self, key: str, default=None) -> Any:
        """
        获取配置项
        
        Args:
            key: 配置键，支持点号分隔的多级键，如 'baidu_ocr.api_key'
            default: 默认值
            
        Returns:
            配置值
        """
        keys = key.split('.')
        value = self._config
        
        for k in keys:
            if isinstance(value, dict):
                value = value.get(k)
            else:
                return default
        
        return value if value is not None else default
    
    def get_all(self) -> Dict[str, Any]:
        """获取所有配置"""
        return self._config.copy()
    
    def reload(self):
        """重新加载配置文件"""
        self._load_config()
        logger.info("配置已重新加载")


# 创建全局配置实例
config = Config()


# 便捷函数
def get_config(key: str, default=None) -> Any:
    """获取配置项的便捷函数"""
    return config.get(key, default)

